package com.example.demo.ordernumber;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author calwen
 * @since 2023/10/8
 */
@Slf4j
@Component
public class OrderNumberUtil {

    @Resource
    private ApplicationContext context;
    private static RedisTemplate redisTemplate;

    @PostConstruct
    public void init() {
        try {
            redisTemplate = context.getBean("redisTemplate", RedisTemplate.class);
        } catch (BeansException e) {
            log.info(" RedisTemplate 未正常注入 ");
        }
    }

    public static String generatorOrderNo() {
        DateTime now = DateTime.now(DateTimeZone.forOffsetHours(8));
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMddHHmmss");
        String orderNo = now.toString(format) + randSafeStr(4);

        //支持redis，则检查 2秒内是否重复生成订单号，重复则重新生成
        if (redisTemplate != null) {
            Boolean b = redisTemplate.opsForValue().setIfAbsent("jcomm:orderno:" + orderNo, "", 2, TimeUnit.SECONDS);
            if (Objects.equals(b, false)) {
                log.info("重复生成订单号 {} ", orderNo);
                count++;
                return generatorOrderNo();
            }
        }
        return orderNo;
    }

    public static int count = 0;
    public static int sum = 0;


    public static String randSafeStr(int num) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        StringBuilder result = new StringBuilder("");
        while (result.length() < num) {
            result.append(random.nextInt(10 * num));
        }
        return result.substring(0, num);
    }
}
